<template>
  <view v-if="visible" class="product-popup">
    <view class="popup-header">
      <view class="product-name">{{ productName }}</view>
      <view class="close-button" @tap="emit('update:visible', false)">✕</view>
    </view>
    <view class="quantity-control">
      <view class="quantity-label">数量：</view>
      <view class="quantity-buttons">
        <view class="quantity-button minus" @tap="decreaseQutity">-</view>
        <view class="quantity-value">{{ localQutity }}</view>
        <view class="quantity-button plus" @tap="increaseQutity">+</view>
      </view>
      <view class="remove-button" @tap="removeProduct">移除商品</view>
    </view>
    <view class="total-price">小计：¥{{ total }}</view>
    <view class="confirm-button" @tap="confirmPopup">确定</view>
  </view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';

const props = defineProps({
  visible: Boolean,
  productName: String,
  qutity: Number,
  retailPrice: Number,
  index: Number
});

const emit = defineEmits(['update:visible', 'remove', 'confirm']);

// 使用本地变量存储数量，以便于内部操作
const localQutity = ref(props.qutity);

// 监听传入的 qutity 值变化并更新本地变量
watch(() => props.qutity, (newVal) => {
  localQutity.value = newVal;
});

const total = computed(() => localQutity.value * props.retailPrice);

function decreaseQutity() {
  if (localQutity.value > 0) {
    localQutity.value--;
  }
}

function increaseQutity() {
  localQutity.value++;
}

function removeProduct() {
  emit('remove', props.index);
  emit('update:visible', false);
}

function confirmPopup() {
  emit('confirm', { index: props.index, qutity: localQutity.value });
  emit('update:visible', false);
}
</script>

<style scoped>
.product-popup {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.close-button {
  font-size: 24px;
  cursor: pointer;
}

.quantity-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.quantity-label {
  margin-right: 10px;
}

.quantity-buttons {
  display: flex;
  align-items: center;
}

.quantity-button {
  width: 30px;
  height: 30px;
  background-color: #fff;
  border: 1px solid #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.quantity-value {
  margin: 0 10px;
  font-weight: bold;
}

.remove-button {
  color: red;
  cursor: pointer;
}

.total-price {
  text-align: right;
  margin-bottom: 20px;
}

.confirm-button {
  width: 100%;
  height: 50px;
  background-color: #007aff;
  color: #fff;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
  line-height: 50px;
}

</style>